package com.navinfo.opentsp.platform.computing.serializer;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Charsets;
import com.navinfo.opentsp.platform.computing.util.DateUtils;
import com.navinfo.opentsp.platform.location.protocol.common.LCChassisDataUpload;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.serialization.EventSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.OutputStream;

/**
* ChassisUpload信息 D00A协议数据上传，
* HDFS_Sink的DBCUpload序列化器，拼接成字段间通过\001分割的字符串
*/
public class HDFSChassisUploadSerializer implements EventSerializer {
    private static final Logger logger = LoggerFactory.getLogger(HDFSChassisUploadSerializer.class);

    private final String APPEND_NEWLINE = "appendNewline";
    private final boolean appendNewline;
    private final String splitStr = "\001";
    private final OutputStream out;

    private HDFSChassisUploadSerializer(OutputStream out, Context ctx) {
        this.appendNewline = ctx.getBoolean(APPEND_NEWLINE, true);
        this.out = out;
    }

    @Override
    public boolean supportsReopen() {
        return false;
    }
    @Override
    public void afterCreate() {}
    @Override
    public void afterReopen() {}
    @Override
    public void beforeClose() {}
    @Override
    public void flush() throws IOException {
        this.out.flush();
    }
    @Override
    public void write(Event event) throws IOException {
        try {
//            logger.error(event.toString());
            //拼写落盘到HDFS的字符串。字段间分隔符是\001，null通过\N表示
            LCChassisDataUpload.ChassisDataUpload chassisDataUpload = LCChassisDataUpload.ChassisDataUpload.parseFrom(event.getBody());
            StringBuilder chassisUploadStr = new StringBuilder(5000);

            chassisUploadStr.append(chassisDataUpload.getLatitude()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getLongitude()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getOriginalLat()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getOriginalLng()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getHeight()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getDirection()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getGpsDate()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getVersion()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getEngineIntakeManifoldPressure()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getEngineIntakeManifoldTemperature()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getEngineCoolantTemperature()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getFuelTemperature()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getAmbientTemperature()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getInstrumentSpeed()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getRotation()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getServiceBrakeCircuit1AirPressure()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getServiceBrakeCircuit2AirPressure()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getFanSpeed()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getAccumulatedMileage()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getSubtotalMileage()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getAcceleratorPedalPosition()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getCurrentRotationLoad()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getServiceBrake()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getEscInstrumentLightSignal()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getAbsActivationStatus()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getEscFullActivation()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getEscBrakeLightRequestSignal()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getAntiRolloverActivationEngine()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getAntiRolloverActivationServiceBrake()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getDirectionControlActivatesEngine()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getDirectionControlActivatesServiceBrake()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getEscActivateTrailer()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getSteeringWheelAngleSensorType()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getExhaustBrakingState()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getInCylinderBrake2Status()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getInCylinderBrake1Status()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getSteeringWheelTurnsNumber()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getAuxiliaryBrakeGear()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getSteeringWheelAngle()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getYawRate()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getLateralAcceleration()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getLongitudinalAcceleration()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getBrakePedalTravel()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getFrontWheelSpeed()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getRearAxleOneLeftWheelSpeed()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getRearAxleOneRightWheelSpeed()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getRearAxleTwoLeftWheelSpeed()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getRearAxleTwoRightWheelSpeed()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getErc1ActualTorquePercentageRetarder()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getErc1MaximumTorquePercentageRetarder()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getErc1ActualTorquePercentageEngine()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getErc1MaximumTorquePercentageEngine()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getTerminalId()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getSerialNumber()).append(splitStr);
            chassisUploadStr.append(chassisDataUpload.getRetransmissionPackets()).append(splitStr);

            //添加字段只能在分割线之上添加,注意时间分区这块，终端传的时候是秒还是毫秒
            //------------------------------------------分割线----------------------------------------
            chassisUploadStr.append(DateUtils.format(chassisDataUpload.getGpsDate() * 1000, "yyyyMMdd"));
//            logger.error(dataJson);
            //将数据拼接后写入hdfs
            this.out.write(chassisUploadStr.toString().getBytes(Charsets.UTF_8));
            if (this.appendNewline) {
                this.out.write(10);
            }
        }catch (Exception e){
            logger.error("执行HDFS的HDFSChassisUploadSerializer拦截器失败：" + e.getMessage(), e);
        }
    }

//    public static List<String> getMaintenanceEvents(List<LCLocationData.StaytimeParkingAddition> staytimeParkings){
//        List<String> staytimeParkingDtos = Lists.newArrayList();
//        if(staytimeParkings == null){
//            return staytimeParkingDtos;
//        }
//        for(LCLocationData.StaytimeParkingAddition staytimeParking : staytimeParkings){
//            staytimeParkingDtos.add(StaytimeParkingAdditionDto.parseString(staytimeParking));
//        }
//        return staytimeParkingDtos;
//    }


    public static class Builder implements EventSerializer.Builder {
        public Builder() { }
        @Override
        public EventSerializer build(Context context, OutputStream out) {
            return  new HDFSChassisUploadSerializer(out, context);
        }
    }
}
